: incbin - A utility for including binary files in C source.
:          Given a binary file and a C symbol name, generates
:          a .h or .c file with that binary data stored as an
:          array of unsigned chars.
:
:          This script has no non-standard dependencies and runs
:          on both Windows and UNIX.
:
:          http://github.com/rmitton/incbin
:
: Usage:
: Windows: incbin.bat myfile.bin output.h symbolname
: UNIX:    sh incbin.bat myfile.bin output.h symbolname
:
:          ; if false ; then #lolwut
#!/bin/bash

<!--- : Begin batch script ---

@echo off
cscript //nologo "%~f0?.wsf" %*
exit /b

<<'EOF'
--- Begin wsf script --->

<job><script language="VBScript">

Set fso = Wscript.CreateObject("Scripting.FileSystemObject")
Set stderr = fso.GetStandardStream(2)

On Error Resume Next

inpath = Wscript.Arguments(0)
outpath = Wscript.Arguments(1)
symbol = Wscript.Arguments(2)
If Err.Number <> 0 Then
	stderr.WriteLine "Usage: incbin input.bin output.h symbolname"
    WScript.Quit 1
End If

Set ts = fso.getFile(inpath).OpenAsTextStream()
If Err.Number <> 0 Then
	stderr.WriteLine inpath & ": " & Err.Description
    WScript.Quit 1
End If

Set outf = fso.CreateTextFile(outpath, True, False)
If Err.Number <> 0 Then
	stderr.WriteLine outpath & ": " & Err.Description
    WScript.Quit 1
End If

outf.WriteLine("/* Generated by incbin */" & vbCrLf & vbCrLf & "#include <stddef.h>" & vbCrLf)
outf.WriteLine("const unsigned char " & symbol & "_data[] = {")

offset = 0
While Not ts.atEndOfStream
	If offset Mod 16 = 0 Then
		If offset > 0 Then outf.WriteLine(",")
		outf.Write("/*")
		offstr = Hex(offset)
		While Len(offstr) < 8
			offstr = "0" & offstr
		Wend
		outf.Write(offstr & "*/ ")
	Else
		outf.Write(",")
	End If
    byteval = AscB(ts.Read(1))
    hexstr = Hex(byteval)
    If byteval < 16 Then hexstr = "0" & hexstr
    outf.Write("0x" & hexstr)
    offset = offset + 1
Wend

outf.WriteLine(vbCrLf & "};" & vbCrLf)
outf.WriteLine("const size_t " & symbol & "_size = sizeof(" & symbol & "_data);")

ts.Close()
outf.Close()

</script></job><!---

EOF
fi

# --- Begin sh script ---

set -e

usage () {
	echo Usage: incbin input.bin output.h symbolname
	exit 1
}

[ -z "$1" ] && usage
[ -z "$2" ] && usage
[ -z "$3" ] && usage
bytes=`od -An -t x1 -v "$1"`

(
	echo "/* Generated by incbin */"
	echo
	echo "#include <stddef.h>"
	echo
	echo "const unsigned char $3_data[] = {"

	offset=0 ; count=16
	for val in $bytes ; do
		if [ $count -eq 16 ] ; then
			if [ $offset -ne 0 ] ; then
				echo ,
			fi
			printf "/*%08x*/ " $offset
			count=0
		else
			printf ,
		fi
		printf 0x$val

		offset=$(($offset+1)) ; count=$(($count+1))
	done
	echo
	echo "};"
	echo
	echo "const size_t $3_size = sizeof($3_data);"
) > "$2"

# --->
